import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/search_controller.dart' as search;

class SearchView extends GetView<search.SearchController> {
  const SearchView({super.key});

  @override
  Widget build(BuildContext context) {
    // 设置状态栏为黑色文字
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
    );

    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      body: SafeArea(
        child: GestureDetector(
          onTap: () {
            // 点击空白区域隐藏键盘
            FocusScope.of(context).unfocus();
          },
          child: Column(
            children: [
              // 搜索栏
              _buildSearchBar(context),
              // 内容区域
              Expanded(
                child: Obx(() {
                  if (controller.showSearchResults.value) {
                    // 显示搜索结果
                    return _buildSearchResults();
                  } else {
                    // 显示历史记录或空状态
                    return _buildHistoryOrEmpty();
                  }
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建搜索栏
  Widget _buildSearchBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(30.w),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              width: 88.w,
              height: 88.w,
              margin: EdgeInsets.only(right: 20.w),
              child: Icon(
                Icons.arrow_back_ios_new,
                size: 32.w,
                color: const Color(0xFF333333),
              ),
            ),
          ),
          // 搜索输入框 - 使用Expanded防止溢出
          Expanded(
            child: Container(
              height: 74.h,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(14.r),
              ),
              child: TextField(
                controller: controller.searchEditingController,
                onSubmitted: controller.onSearchSubmitted,
                onChanged: controller.onSearchChanged,
                autofocus: true,
                textInputAction: TextInputAction.search, // 设置键盘为搜索按钮
                style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF333333),
                ),
                decoration: InputDecoration(
                  isDense: true,
                  hintText: '通道名称',
                  hintStyle: TextStyle(
                    fontSize: 28.sp,
                    color: const Color(0xFF999999),
                  ),
                  prefixIcon: Icon(
                    Icons.search,
                    size: 40.w,
                    color: const Color(0xFF999999),
                  ),
                  suffixIcon: Obx(() {
                    return controller.searchText.value.isNotEmpty
                        ? GestureDetector(
                          onTap: controller.clearSearchResults,
                          child: Icon(
                            Icons.clear,
                            size: 40.w,
                            color: const Color(0xFF999999),
                          ),
                        )
                        : const SizedBox.shrink();
                  }),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 24.w,
                    vertical: 20.w,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建历史记录或空状态
  Widget _buildHistoryOrEmpty() {
    return Obx(() {
      if (controller.historyList.isEmpty) {
        return _buildEmptyState();
      } else {
        return _buildHistoryContent();
      }
    });
  }

  /// 构建历史记录内容
  Widget _buildHistoryContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 历史记录标题栏
        _buildHistoryHeader(),
        // 历史记录标签
        _buildHistoryTags(),
        // 空状态
        Expanded(child: _buildEmptySearchState()),
      ],
    );
  }

  /// 构建历史记录标题栏
  Widget _buildHistoryHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '历史记录',
            style: TextStyle(
              fontSize: 32.sp,
              fontWeight: FontWeight.w500,
              color: const Color(0xFF333333),
            ),
          ),
          GestureDetector(
            onTap: () {
              // 隐藏键盘
              FocusScope.of(Get.context!).unfocus();
              // 清空历史记录
              controller.clearAllHistory();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 8.w),
              child: Text(
                '清空',
                style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF4A90E2),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建历史记录标签
  Widget _buildHistoryTags() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30.w),
      child: Obx(() {
        return Wrap(
          spacing: 20.w,
          runSpacing: 16.w,
          children:
              controller.historyList.map((keyword) {
                return GestureDetector(
                  onTap: () {
                    // 隐藏键盘
                    FocusScope.of(Get.context!).unfocus();
                    // 点击历史记录项
                    controller.onHistoryItemTap(keyword);
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 24.w,
                      vertical: 12.w,
                    ),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF5F6FA),
                      borderRadius: BorderRadius.circular(20.w),
                      border: Border.all(
                        color: const Color(0xFFE0E0E0),
                        width: 1.w,
                      ),
                    ),
                    child: Text(
                      keyword,
                      style: TextStyle(
                        fontSize: 26.sp,
                        color: const Color(0xFF666666),
                      ),
                    ),
                  ),
                );
              }).toList(),
        );
      }),
    );
  }

  /// 构建空搜索状态
  Widget _buildEmptySearchState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 空状态图片
          Image.asset('assets/images/null.png', width: 378.w, height: 378.w),
          SizedBox(height: 40.w),
          Text(
            '暂无搜索',
            style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
          ),
        ],
      ),
    );
  }

  /// 构建空状态（无历史记录）
  Widget _buildEmptyState() {
    return _buildEmptySearchState();
  }

  /// 构建搜索结果
  Widget _buildSearchResults() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 搜索结果标题
        Container(
          padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 20.w),
          child: Obx(() {
            return Text(
              '搜索"${controller.searchKeyword.value}"的结果',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF666666)),
            );
          }),
        ),
        // 搜索结果列表
        Expanded(
          child: Obx(() {
            if (controller.isSearching.value) {
              return _buildLoadingState();
            }
            if (controller.searchResults.isEmpty) {
              return _buildNoResults();
            }
            return ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              itemCount: controller.searchResults.length,
              itemBuilder: (context, index) {
                final result = controller.searchResults[index];
                return _buildSearchResultItem(result);
              },
            );
          }),
        ),
      ],
    );
  }

  /// 构建无搜索结果
  Widget _buildNoResults() {
    return _buildEmptySearchState();
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 40.w,
            height: 40.w,
            child: const CircularProgressIndicator(),
          ),
          SizedBox(height: 20.h),
          Text(
            '搜索中...',
            style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
          ),
        ],
      ),
    );
  }

  /// 构建搜索结果项
  Widget _buildSearchResultItem(Map<String, dynamic> result) {
    final channelName = result['name']?.toString() ?? '未知设备';
    final hsId = result['hsId']?.toString() ?? '';
    final isOnline = result['status'] == 'ON';

    return GestureDetector(
      onTap: () {
        // 隐藏键盘
        FocusScope.of(Get.context!).unfocus();
        // 跳转到设备详情页面
        Get.toNamed(
          '/device-detail',
          arguments: {
            'hsId': hsId,
            'deviceId': result['deviceId']?.toString() ?? '',
            'channelId': result['channelId']?.toString() ?? '',
            'deviceName': channelName,
          },
        );
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 20.w),
        padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 24.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.w),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.05),
              offset: const Offset(0, 2),
              blurRadius: 8,
            ),
          ],
        ),
        child: Row(
          children: [
            // 设备状态图标
            Container(
              width: 32.w,
              height: 32.h,
              decoration: BoxDecoration(
                color:
                    isOnline
                        ? const Color(0xFF0ACA00)
                        : const Color(0xFFD8D8D8),
                shape: BoxShape.circle,
              ),
              child: Icon(
                isOnline ? Icons.videocam : Icons.videocam_off,
                size: 16.w,
                color: Colors.white,
              ),
            ),
            SizedBox(width: 20.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    channelName,
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w500,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    isOnline ? '在线' : '离线',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color:
                          isOnline
                              ? const Color(0xFF0ACA00)
                              : const Color(0xFF999999),
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 24.w,
              color: const Color(0xFF999999),
            ),
          ],
        ),
      ),
    );
  }
}
